'use client';

import React, { useState } from 'react';
import { Form, Input, Select, Row, Col, Radio, Button, Card, Space, Typography, InputNumber, Divider } from 'antd';
import { CalendarOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/es/form';

const { TextArea } = Input;
const { Option } = Select;
const { Text } = Typography;

// 订单类型选项
const orderTypeOptions = [
  { label: '工程师操作', value: 'engineer_operation' },
  { label: '自主操作', value: 'self_operation' },
];

// 实验类型选项
const experimentTypeOptions = [
  { label: '常规实验', value: 'normal' },
  { label: '培训实验', value: 'training' },
  { label: '研发实验', value: 'research' },
];

// 样品类型选项
const sampleTypeOptions = [
  { label: '自带', value: 'self_bring' },
  { label: '出样', value: 'sample_out' },
];

// 精品选项
const sampleQualityOptions = [
  { label: '不限制', value: 'unlimited' },
  { label: '限制', value: 'limited' },
];

// 支付方式选项
const paymentMethodOptions = [
  { label: '个人余额账户', value: 'personal_balance' },
  { label: '课题组余额', value: 'group_balance' },
  { label: '对公转账', value: 'bank_transfer' },
  { label: '现金支付', value: 'cash' },
];

// 模拟耗材数据
const mockConsumables = [
  { id: '1', name: '耗材1', price: 500, unit: '个' },
  { id: '2', name: '耗材2', price: 300, unit: '个' },
  { id: '3', name: '耗材3', price: 200, unit: '个' },
];

// 模拟增值服务数据
const mockServices = [
  { id: '1', name: '数据分析', price: 500, unit: '次' },
  { id: '2', name: '报告撰写', price: 800, unit: '份' },
  { id: '3', name: '样品预处理', price: 300, unit: '次' },
];

interface OrderBasicFormProps {
  form: FormInstance;
  mode: 'create' | 'edit' | 'view';
  initialValues?: Record<string, unknown>;
  onSubmit?: (values: Record<string, unknown>) => void;
}

interface ReservationTime {
  start: string;
  end: string;
}

interface ConsumableItem {
  id: string;
  name: string;
  price: number;
  unit: string;
  quantity: number;
}

interface ServiceItem {
  id: string;
  name: string;
  price: number;
  unit: string;
  quantity: number;
}

const OrderBasicForm: React.FC<OrderBasicFormProps> = ({ 
  form, 
  mode, 
  initialValues = {},
  onSubmit 
}) => {
  const isReadOnly = mode === 'view';
  const [selectedConsumables, setSelectedConsumables] = useState<ConsumableItem[]>([]);
  const [selectedServices, setSelectedServices] = useState<ServiceItem[]>([]);
  const [reservationTimes] = useState<ReservationTime[]>([
    { start: '2025-03-28 9:00', end: '2025-03-28 11:00' },
    { start: '2025-03-29 9:00', end: '2025-03-29 11:00' }
  ]);

  // 处理预约时间选择
  const handleReservationSelect = () => {
    // TODO: 打开时间选择弹窗
    console.log('选择预约时间');
  };

  // 处理耗材选择
  const handleConsumableSelect = (consumableId: string, quantity: number) => {
    const consumable = mockConsumables.find(item => item.id === consumableId);
    if (consumable) {
      const existing = selectedConsumables.find(item => item.id === consumableId);
      if (existing) {
        setSelectedConsumables(prev => 
          prev.map(item => 
            item.id === consumableId ? { ...item, quantity } : item
          )
        );
      } else {
        setSelectedConsumables(prev => [...prev, { ...consumable, quantity }]);
      }
    }
  };

  // 处理增值服务选择
  const handleServiceSelect = (serviceId: string, quantity: number) => {
    const service = mockServices.find(item => item.id === serviceId);
    if (service) {
      const existing = selectedServices.find(item => item.id === serviceId);
      if (existing) {
        setSelectedServices(prev => 
          prev.map(item => 
            item.id === serviceId ? { ...item, quantity } : item
          )
        );
      } else {
        setSelectedServices(prev => [...prev, { ...service, quantity }]);
      }
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onSubmit}
      initialValues={{
        instrumentName: '等离子体发射光谱仪(ICP-OES)',
        orderType: 'engineer_operation',
        experimentType: 'normal',
        sampleType: 'self_bring',
        sampleQuality: 'unlimited',
        paymentMethod: 'personal_balance',
        ...initialValues
      }}
      disabled={isReadOnly}
    >
      {/* 仪器信息 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item
            label="仪器名称"
            name="instrumentName"
          >
            <Input 
              value="等离子体发射光谱仪(ICP-OES)" 
              readOnly 
              style={{ fontWeight: 'bold', fontSize: '16px' }}
            />
          </Form.Item>
        </Col>
      </Row>

      {/* 订单类型 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item
            label="订单类型"
            name="orderType"
            rules={[{ required: !isReadOnly, message: '请选择订单类型' }]}
          >
            <Radio.Group disabled={isReadOnly}>
              {orderTypeOptions.map(option => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
        </Col>
      </Row>

      {/* 实验类型 */}
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item
            label="实验类型"
            name="experimentType"
            rules={[{ required: !isReadOnly, message: '请选择实验类型' }]}
          >
            <Select placeholder="选择实验类型" disabled={isReadOnly}>
              {experimentTypeOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="样品类型"
            name="sampleType"
          >
            <Radio.Group disabled={isReadOnly}>
              {sampleTypeOptions.map(option => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
        </Col>
      </Row>

      {/* 精品选择 */}
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item
            label="精品"
            name="sampleQuality"
          >
            <Radio.Group disabled={isReadOnly}>
              {sampleQualityOptions.map(option => (
                <Radio key={option.value} value={option.value}>
                  {option.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="样品限制">
            <Text type="secondary">
              (即样品应满足检测标准的前处理要求和样品量要求)
            </Text>
          </Form.Item>
        </Col>
      </Row>

      {/* 预约信息 */}
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="预约信息">
            <Button 
              icon={<CalendarOutlined />}
              onClick={handleReservationSelect}
              disabled={isReadOnly}
              style={{ width: '100%' }}
            >
              点击选择/修改
            </Button>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="预约时间">
            <Button 
              icon={<ClockCircleOutlined />}
              onClick={handleReservationSelect}
              disabled={isReadOnly}
              style={{ width: '100%' }}
            >
              点击选择/修改
            </Button>
          </Form.Item>
        </Col>
      </Row>

      {/* 已选时间 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item label="已选时间">
            <Card size="small">
              {reservationTimes.map((time, index) => (
                <div key={index} style={{ marginBottom: index < reservationTimes.length - 1 ? 8 : 0 }}>
                  <Text>{time.start} - {time.end}</Text>
                </div>
              ))}
              <div style={{ marginTop: 8 }}>
                <Text type="secondary">实验预计时长: 4 小时</Text>
              </div>
            </Card>
          </Form.Item>
        </Col>
      </Row>

      {/* 备注 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item
            label="备注"
            name="remark"
          >
            <TextArea
              rows={4}
              placeholder="请输入"
              readOnly={isReadOnly}
            />
          </Form.Item>
        </Col>
      </Row>

      <Divider />

      {/* 耗材选择 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item label="耗材">
            <Select placeholder="选择耗材" disabled={isReadOnly} style={{ width: '100%' }}>
              {mockConsumables.map(consumable => (
                <Option key={consumable.id} value={consumable.id}>
                  {consumable.name}
                </Option>
              ))}
            </Select>
            <div style={{ marginTop: 16 }}>
              {mockConsumables.map(consumable => (
                <Row key={consumable.id} gutter={16} style={{ marginBottom: 8, alignItems: 'center' }}>
                  <Col span={8}>
                    <Text>{consumable.name} {consumable.price}元/{consumable.unit}</Text>
                  </Col>
                  <Col span={4}>
                    <InputNumber
                      min={0}
                      max={10}
                      defaultValue={1}
                      disabled={isReadOnly}
                      onChange={(value) => handleConsumableSelect(consumable.id, value || 0)}
                    />
                  </Col>
                  <Col span={2}>
                    <Button 
                      type="link" 
                      size="small"
                      disabled={isReadOnly}
                    >
                      删除
                    </Button>
                  </Col>
                </Row>
              ))}
            </div>
          </Form.Item>
        </Col>
      </Row>

      {/* 增值服务 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item label="增值服务">
            <Select placeholder="选择增值服务" disabled={isReadOnly} style={{ width: '100%' }}>
              {mockServices.map(service => (
                <Option key={service.id} value={service.id}>
                  {service.name}
                </Option>
              ))}
            </Select>
            <div style={{ marginTop: 16 }}>
              {mockServices.map(service => (
                <Row key={service.id} gutter={16} style={{ marginBottom: 8, alignItems: 'center' }}>
                  <Col span={8}>
                    <Text>{service.name} {service.price}元</Text>
                  </Col>
                  <Col span={4}>
                    <InputNumber
                      min={0}
                      max={10}
                      defaultValue={0}
                      disabled={isReadOnly}
                      onChange={(value) => handleServiceSelect(service.id, value || 0)}
                    />
                  </Col>
                  <Col span={2}>
                    <Button 
                      type="link" 
                      size="small"
                      disabled={isReadOnly}
                    >
                      删除
                    </Button>
                  </Col>
                </Row>
              ))}
            </div>
          </Form.Item>
        </Col>
      </Row>

      <Divider />

      {/* 仪器收费方式 */}
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="仪器收费方式">
            <Text>联机时 1000元/小时</Text>
          </Form.Item>
        </Col>
      </Row>

      {/* 费用信息 */}
      <Row gutter={24}>
        <Col span={12}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Text>预估金额:</Text>
              <Text strong>1000.00 元/小时</Text>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Text>耗材金额:</Text>
              <Text>1400.00 元</Text>
            </div>
          </Space>
        </Col>
      </Row>

      {/* 支付方式 */}
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item
            label="支付方式"
            name="paymentMethod"
            rules={[{ required: !isReadOnly, message: '请选择支付方式' }]}
          >
            <Radio.Group disabled={isReadOnly}>
              <Space direction="vertical">
                {paymentMethodOptions.map(option => (
                  <Radio key={option.value} value={option.value}>
                    {option.label}
                    {option.value === 'personal_balance' && (
                      <Text type="secondary"> (当前可用余额: 00.00元)</Text>
                    )}
                    {option.value === 'group_balance' && (
                      <Text type="secondary"> (当前可用余额: 00.00元)</Text>
                    )}
                    {option.value === 'bank_transfer' && (
                      <Text type="secondary"> 可打折</Text>
                    )}
                    {option.value === 'cash' && (
                      <Text type="secondary"> 可打7折</Text>
                    )}
                  </Radio>
                ))}
              </Space>
            </Radio.Group>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

export default OrderBasicForm; 